import urllib2, re
import vkontakte.auth
from vkontakte.common import unescape

class FriendsFetcher:
    def __init__(self, vkontakte_auth):
        self._auth = vkontakte_auth
        self._friends_list = []
        
    def fetch_list(self):
        opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self._auth.get_cookie()))
        response = opener.open('http://vkontakte.ru/friend.php')
        udata = unescape(unicode(response.read(), 'windows-1251'))
        f = re.findall(r"\[(\d+), {f:'([^']*)', l:'([^']*)'}", udata)
        self._friends_list = [(i, "%s %s" % (fname, lname)) for (i, fname, lname) in f]
        
    def GetFriends(self):
        if len(self._friends_list) == 0:
            self.fetch_list()
        
        return self._friends_list
            
    